<template>
  <div>
    <div id="Content">
      <div id="BackLink">
        <router-link to="/">Return to Main Menu</router-link>
      </div>

      <div id="Catalog">
        <table>
          <tr>
            <th>&nbsp;</th>
            <th>Product ID</th>
            <th>EnglishName</th>
            <th>ChineseName</th>
          </tr>
          <tr v-for="product in filteredProducts" :key="product.productId">
            <td>
              <a :href="'/catalog/viewProduct?productId=' + product.productId" name="productId" :value="product.productId">
                <div :th:with="desc = product.productImage">
                  <span>{{ desc.substring(0, desc.indexOf('<')) }}</span>
                  <img :src="'../../' + desc.replace(/.*src=&quot;([^&quot;]+)&quot;.*/, '$1')" :alt="desc.replace(/.*src=&quot;[^&quot;]+&quot;(.*)/, '$1')">
                  <span>{{ desc.substring(desc.lastIndexOf('>') + 1) }}</span>
                </div>
              </a>
            </td>
            <td>
              <b>
                <a :href="'/catalog/viewProduct?productId=' + product.productId" name="productId" :value="product.productId">
                  <span style="color: black">{{ product.productId }}</span>
                </a>
              </b>
            </td>
            <td>{{ product.productNameEnglish }}</td>
            <td>{{ product.productNameChinese }}</td>
          </tr>
          <tr>
            <td></td>
          </tr>
        </table>
      </div>
    </div>
    <bottom />
  </div>
</template>

<script>
import top from "../../components/common/top.vue";
import bottom from "../../components/common/bottom.vue";
import axios from 'axios'; // 导入axios库

export default {
  components: {
    top,
    bottom,
  },
  data() {
    return {
      productList: [],
      keyword: '' // 添加关键字数据属性
    };
  },
  mounted() {
    this.keyword = this.$route.params.keyword; // 获取路由参数中的关键字
    this.fetchProductList(); // 页面加载时获取产品列表
  },
  computed: {
    filteredProducts() {
      // 根据关键字筛选产品列表
      return this.productList.filter((product) =>
          product.productNameEnglish && product.productNameEnglish.toLowerCase().includes(this.keyword.toLowerCase())
      );
    },
  },
  methods: {
    fetchProductList() {
      // 发送HTTP GET请求获取产品列表数据
      axios.get(`http://localhost:8080/jpetstore/pets/search?keyword=${this.keyword}`)
          .then(response => {
            console.log(response.data.data);
            this.productList = response.data.data; // 将获取到的产品列表数据保存到data中的productList
          })
          .catch(error => {
            console.error('Error fetching product list:', error);
          });
    },
  },
};
</script>

<style scoped>
</style>
